package com.cetc;

import com.cetc.domain.Person;
import org.junit.Test;

import java.util.Random;

/**
 * @Classname NewInstanceTest02
 * @Description 通过反射创建对象
 * @Date 2022/12/8 20:14
 * @Created by louzhuangxi
 */
public class NewInstanceTest02 {

    /**
     * 调用无参构造创建对象,构造器的访问权限需要是public
     */
    @Test
    public void test01() throws InstantiationException, IllegalAccessException {
        Class<Person> clazz = Person.class;
        Person person = clazz.newInstance();
        System.out.println(person);
    }

    /**
     * 测试反射的动态性
     */
    @Test
    public void test02() {
        for (int i = 0; i < 1000; i++) {
            int num = new Random().nextInt(3);
            System.out.println("随机数为：" + num);
            String classPath;
            switch (num) {
                case 0:
                    classPath = "java.util.Date";
                    break;
                case 1:
                    classPath = "java.util.Random";
                    break;
                case 2:
                    classPath = "java.lang.String";
                    break;
                default:
                    classPath = "java.lang.Integer";
            }
            Object instance = null;
            try {
                instance = getInstance(classPath);
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println(instance);
        }
    }

    public Object getInstance(String classPath) throws Exception {
        Class<?> clazz = Class.forName(classPath);
        return clazz.newInstance();
    }
}
